import { defineStore } from "pinia";
import { store } from "/@/store";
import { ReqParams } from "/@/api/user/model";
import fetchApi from "/@/api/user";
// import { encryptByDES } from '/@/utils/crypto';
import { getToken, setToken, removeToken } from "/@/utils/auth";
import { router } from "/@/router";

interface UserState {
  token: string;
  auths: string[];
}

export const useUserStore = defineStore({
  id: "app-user",
  state: (): UserState => ({
    token: "",
    auths: [],
  }),
  getters: {
    getToken(): string {
      return this.token || getToken();
    },
  },
  actions: {
    setToken(info: string) {
      this.token = info ?? "";
      setToken(info);
    },
    setAuth(auths: string[]) {
      this.auths = auths;
    },
    resetState() {
      this.token = "";
      this.auths = [];
    },
    async login(params: ReqParams) {
      const res = await fetchApi.login(params);
      if (res) {
        this.setToken(res.token);
      }
      return res;
    },
    async logout() {
      this.resetState();
      removeToken();
      router.replace("/login");
      location.reload();
    },
  },
});
